package cn.kgc.controller;

import cn.kgc.base.entity.CartSkuInfo;
import cn.kgc.base.vo.OrderItemVo;
import cn.kgc.client.CartSkuInfoFeignClient;
import cn.kgc.commons.util.RedisUtil;
import cn.kgc.commons.util.UserContextHolder;
import cn.kgc.commons.vo.Result;
import cn.kgc.entity.Cart;
import cn.kgc.entity.CartItem;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;

/**
 * <p>添加描述信息</p>
 *
 * @author 卢传琪
 */
@RestController
@Api(tags = "购物车模块")
@RequestMapping("/cart")
public class CartController {

    @Resource
    private RedisUtil redisUtil;
    @Resource
    private CartSkuInfoFeignClient cartSkuInfoFeignClient;

    @GetMapping("/getOrderItemVo")
    @ApiOperation(value = "根据用户id获得购物车中被选中的商品信息", httpMethod = "GET",
            produces = "application/json;charset=utf-8",response = Result.class)
    @ApiImplicitParam(name = "memberId",value = "用户id",dataType = "long",paramType = "query")
    @CrossOrigin
    public List<OrderItemVo> getOrderItemVo(@RequestParam(name = "memberId") long memberId){
        List<OrderItemVo> result=new ArrayList<>();
        String cartKey=memberId+":cart";
        if (!redisUtil.hasKey(cartKey)){
            return result;
        }
        Iterator<Object> iterator=redisUtil.getHash(cartKey).values().iterator();
        while (iterator.hasNext()){
            CartItem cartItem=(CartItem) iterator.next();
            if (cartItem.isCheck()){//是否选中
                OrderItemVo orderItemVo=new OrderItemVo();
                BeanUtils.copyProperties(cartItem,orderItemVo);
                result.add(orderItemVo);
            }
        }
        return result;
    }

    /**
     * 像购物车中添加商品信息
     * @param skuId
     * @param count
     * @return 是否添加成功
     */
    @PostMapping("/save")
    @ApiOperation(value = "像购物车中添加商品信息", produces = "application/json;charset=utf-8",
            httpMethod = "POST", response = Result.class)
    @ApiImplicitParams({
            @ApiImplicitParam(name = "skuId", value = "skuId",paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "count", value = "购买商品数量",paramType = "query", dataType = "Integer")
    })
    public boolean saveCartItem(@RequestParam(name = "skuId") Long skuId,
                                @RequestParam(name = "count",defaultValue = "1") Integer count){
        // 登录的用户id
        String userId=UserContextHolder.getInstance().getUserId();
        String cacheKey=userId+":cart";
        //hk
        String hk=skuId+"";
        //hv

        //判断购物车中是否有该商品
        // (2) 购物车中有该商品，将商品的数量进行累加
        if (redisUtil.hasKey(cacheKey,hk)){
            //获取购物车中的商品信息
            CartItem cartItem=(CartItem) redisUtil.get(cacheKey,hk);
            //修改商品数量
            cartItem.setCount(cartItem.getCount()+count);
            redisUtil.putKey(cacheKey,hk,cartItem);
            return true;
        }
        // (1) 购物车中没有该商品，将商品放入到购物车中
        // 远程调用接口，创建购物车添加商品信息
        Result<CartSkuInfo> result=cartSkuInfoFeignClient.getCartSkuInfo(skuId);
        if (result.getData()==null){//服务降级，没有获得商品的信息
            return false; //添加失败
        }
        CartSkuInfo cartSkuInfo=result.getData();
        CartItem hv=new CartItem();
        hv.setSkuId(cartSkuInfo.getSkuId());
        hv.setSpuId(cartSkuInfo.getSpuId());
        hv.setSkuAttr(cartSkuInfo.getSkuAttr());
        hv.setImage(cartSkuInfo.getImage());
        hv.setTitle(cartSkuInfo.getTitle());
        hv.setPrice(cartSkuInfo.getPrice());
        hv.setCount(count);
        hv.setCheck(true);
        redisUtil.putKey(cacheKey,hk,hv);
        // 将商品保存到redis中   hash类型保存数据
        // key:用户的的id_cart  hk:skuId     hv:CartItem对象
        // (1) 购物车中没有该商品，将商品放入到购物车中
        // (2) 购物车中有该商品，将商品的数量进行累加
        return true;
    }
    //查看购物车的商品
    @GetMapping("/getCart")
    @ApiOperation(value = "查看购物车信息",httpMethod = "GET",
            produces = "application/json;charest=utf-8",response = Result.class)
    @CrossOrigin
    public Cart getCart(){
        Cart cart=new Cart();
        //获取购物车中的商品信息
        //todo 登录的用户id
        String userId = UserContextHolder.getInstance().getUserId();
        String cacheKey=userId+":cart";
        if (!redisUtil.hasKey(cacheKey)){
           return cart;
        }
        //获得购物车的商品信息
           List<CartItem> cartItems=new ArrayList<>();
            Map<Object, Object> map=redisUtil.getHash(cacheKey);
            Iterator iterator =map.values().iterator();
            while (iterator.hasNext()){
                CartItem cartItem=(CartItem) iterator.next();
                cartItems.add(cartItem);
            }
            cart.setItems(cartItems);
            return cart;
    }
    //删除购物车中的信息
    @DeleteMapping("/delete")
    @ApiOperation(value = "删除购物车中的商品信息",httpMethod = "DELETE",
            produces = "application/json;charset=utf-8",response = Result.class)
    @ApiImplicitParam(name = "skuId", value = "skuId",paramType = "query", dataType = "Integer")
    public boolean deleteCartItem(@RequestParam(name = "skuId") Long skuId){
        //todo 登录的用户id
        String userId = UserContextHolder.getInstance().getUserId();
        String cacheKey=userId+":cart";
        //hk
        String hk=skuId+"";
        //删除购物车中的商品信息
        redisUtil.deleteHashKey(cacheKey,hk);
        return true;
    }
}
